package com.ibm.ops.parser;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import com.ibm.ops.OpstoolConstant;
import com.ibm.ops.domain.report.OpsAuditLogInfosourceReport;
import com.ibm.ops.exception.RetrieveReportDataException;
import com.ibm.ops.persistent.PersistentHandler;

class InfosourceReportParser extends ParserTemplate {

	public InfosourceReportParser(PersistentHandler persistentHanlder) {
		super(persistentHanlder);
		this.report = new OpsAuditLogInfosourceReport();
	}

//	@Override
//	protected OpsAuditLogReport createReport() throws CreateReportException{
//		return new OpsAuditLogInfosourceReport();
//	}

	@Override
	protected List<String> retrieveReportData(String rawContent) throws RetrieveReportDataException{
		String[] content = rawContent.split(OpstoolConstant.INFOSOURCE_REPORT_SPLIT_TAG);
		if(content.length < 3){
			throw new RetrieveReportDataException("There is no Infosource report data today.");
		}
		//handle the last one to delete the useless context
		String lastMsg = content[content.length - 1]; 
		//here read 2 lines 
		BufferedReader br = null;
		br = new LineNumberReader(new StringReader(lastMsg));
		String line = "";
		int count = 0;
		StringBuffer sb = new StringBuffer();
		try {
			while((line = br.readLine()) != null){				
				if(count == 2){
					break;
				}
				sb.append(line).append(OpstoolConstant.SYSTEM_LINE_SEPARATOR);
				if(line.length() > 0){
					count++;
				}				
			}
		} catch (IOException e) {
			e.printStackTrace();
		} finally{
			if(br != null){
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
		content[content.length - 1] = sb.toString();
		String[] usefulData = new String[content.length - 1];
		System.arraycopy(content, 1, usefulData, 0, content.length - 1);
		List<String> result = new ArrayList<String>();
		result = Arrays.asList(usefulData);
		return result;
	}

}
